import { h, Component } from 'preact';
import React, {PropTypes} from 'react';
import ReactDOM from 'react-dom';
import s from './style.scss';

class Portal extends Component {
	static propTypes = {
		children: PropTypes.oneOfType([
			PropTypes.arrayOf(PropTypes.node),
			PropTypes.node
		]),
		lockScroll: PropTypes.bool
	}
	static defaultProps = {
		lockScroll: true
	}

	componentDidMount() {
		if (this.props.lockScroll) {
			document.body.classList.add(s.hideScroll);
		}

		this.renderOverlay();
	}

	componentWillReceiveProps(nextProps) {
		if (nextProps.lockScroll !== this.props.lockScroll) {
			if (nextProps.lockScroll) {
				document.body.classList.add(s.hideScroll);
			} else {
				document.body.classList.remove(s.hideScroll);
			}
		}
	}

	componentDidUpdate() {
		this.renderOverlay();
	}

	componentWillUnmount() {
		this.unrenderOverlay();
		this.unmountOverlayTarget();

		document.body.classList.remove(s.hideScroll);
	}

	mountOverlayTarget() {
		if (!this.overlayTarget) {
			this.overlayTarget = document.createElement('div');
			document.body.appendChild(this.overlayTarget);
		}
	}

	unmountOverlayTarget() {
		if (this.overlayTarget) {
			document.body.removeChild(this.overlayTarget);
			this.overlayTarget = null;
		}
	}

	unrenderOverlay() {
		if (this.overlayTarget) {
			ReactDOM.unmountComponentAtNode(this.overlayTarget);
			this.overlayInstance = null;
		}
	}

	renderOverlay() {
		const overlay = this.props.children ? React.Children.only(this.props.children) : null;

		if (overlay !== null) {
			this.mountOverlayTarget();
			this.overlayInstance = ReactDOM.unstable_renderSubtreeIntoContainer(
				this, overlay, this.overlayTarget
			);
		} else {
			this.unrenderOverlay();
			this.unmountOverlayTarget();
		}
	}

	render() {
		return null;
	}
}

export default Portal;
